// Copyright (c) 2017, Xiaomi, Inc.  All rights reserved.
// This source code is licensed under the Apache License Version 2.0, which
// can be found in the LICENSE file in the root directory of this source tree.

package dsn.rpc.async;

import dsn.api.Table;
import org.slf4j.Logger;

/**
 * Created by weijiesun on 16-11-25.
 */
public final class ClientRequestRound {
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(TableHandler.class);

    dsn.operator.client_operator operator;
    Table.ClientOPCallback callback;
    int timeoutMs;

    String perfCounterTags;
    long createNanoTime;
    long expireNanoTime;
    /**
     * Constructor.
     * @param op
     * @param perf_counter_tags null means disable perf counter.
     */
    public ClientRequestRound(dsn.operator.client_operator op,
                              Table.ClientOPCallback cb,
                              String perf_counter_tags,
                              int timeoutInMilliseconds) {
        operator = op;
        callback = cb;
        timeoutMs = timeoutInMilliseconds;

        perfCounterTags = perf_counter_tags;
        createNanoTime = System.nanoTime();
        expireNanoTime = createNanoTime + timeoutMs * 1000000;
    }

    public dsn.operator.client_operator getOperator() {
        return operator;
    }
    public void setOperator(dsn.operator.client_operator op) {
        operator = op;
    }

    public void thisRoundCompletion() {
        try {
            callback.onCompletion(operator);
        } catch (Throwable ex) {
            // The exception is generated by the user's callback logic, so we don't do much things on it
            logger.debug("{} got exception", operator.toString(), ex);
        }

        if (perfCounterTags != null) {
            // can set perf counters here
            // addQPS(operator.getQPSCounter(), perfCounterTags, 1L);
            // addLatency(operator.getQPSCounter(), perfCounterTags, System.nanoTime() - createNanoTime);
        }
    }
}
